/*
** my_free.c for malloc in /home/dubois_e//Downloads/malloc/1
** 
** Made by remi dubois
** Login   <dubois_e@epitech.net>
** 
** Started on  Wed Jan 30 11:15:21 2013 remi dubois
** Last update Fri Feb  8 16:44:05 2013 remi dubois
*/

#include	"my_malloc.h"

void	check_data(void)
{
  data	*tmp;

  for (tmp = first; tmp->next != NULL; tmp = tmp->next);
  if (tmp->empty == 1 && tmp->size > 4096)
    {
      tmp->size = 4096;
      sbrk(-(tmp->size - 4096));
    }
}

void	connect_empty_data(void)
{
  data	*tmp;

  for (tmp = first; tmp->next != NULL; tmp = tmp->next)
    {
      if (tmp->empty == 1 && tmp->next->empty == 1)
	{
	  tmp->size = tmp->size + tmp->next->size + sizeof(*tmp);
	  tmp->next = tmp->next->next;
	  connect_empty_data();
	  return ;
	}
    }
}

void	free(void *ptr)
{
  data	*tmp;

  if (ptr != NULL)
    {
      tmp = ptr - sizeof(*tmp);
      tmp->empty = 1;
      connect_empty_data();
      check_data();
    }
}
